import CryptoJS from 'crypto-js';
import axios from "axios"
export default function post(url = "", params = {}) {
    var promise
    return new Promise((resolve, reject) => {
        promise = axios.post(url, params)
        promise.then(response => {
            resolve(response.data) //成功
        }).catch(err => {
            reject(err) //失败
        })
    })
}


var appSecret = "3eff7db2edf94b1a96f687c573c25e";
var appId = "smb3d21f47f90cd4224";
// 设置信息
function set({
    appId,
    params,
    appSecret
}) {
    function calcSign(timestamp, nonce, appSecret) {
        var str = "time:" + timestamp + ",nonce:" + nonce + ",appSecret:" + appSecret;
        var sign = CryptoJS.MD5(str).toString();
        return sign;
    }

    var timestamp = Math.round(new Date().getTime() / 1000);
    var nonce = Math.random().toString(36).substr(2);
    var sign = calcSign(timestamp, nonce, appSecret);
    var id = Math.floor(Math.random() * (50 - 1 + 1) + 1);

    let body = {
        "system": {
            "ver": "1.0",
            "appId": appId,
            "sign": sign,
            "time": timestamp,
            "nonce": nonce
        },
        "id": id,
        "params": params
    };
    return body
}

// 获取管理员token
export let getToken = () => {
    let body = set({
        appId,
        appSecret,
        params: {}
    });
    return post("/openapi/accessToken", body);
}


/*
params:{
    {
        "type": "0",
        "deviceId": "7B06****Z396E9",
        "channelId": "0",
        "token": "At_000085fa18f0319046199b2138c04e54"
    }
}
*/
// 获取轻应用播放token
export let getKitToken = (params) => {
    let body = set({
        appId,
        appSecret,
        params
    });
    return post("/openapi/getKitToken", body);
}

// 根据设备序列号获取多个设备信息
export let bindDeviceList = (params) => {
    let body = set({
        appId,
        appSecret,
        params
    });
    return post("/openapi/bindDeviceList", body);
}

window.getToken = getToken;
window.getKitToken = getKitToken;
window.bindDeviceList = bindDeviceList;